﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;

namespace MDP.WebOpenPortal.Controllers
{
    public class SSOAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
                throw new InvalidOperationException("You cannot use [AdminAuthorize] attribute when a child action cache is active");

            if (IsSSOPageRequested(filterContext))
            {
                if (!this.HasAdminAccess(filterContext))
                    this.HandleUnauthorizedRequest(filterContext);
            }
        }

        private bool IsSSOPageRequested(AuthorizationContext filterContext)
        {
            //var adminAttributes = GetAdminAuthorizeAttributes(filterContext.ActionDescriptor);
            //if (adminAttributes != null && adminAttributes.Any())
            return true;
            //return false;
        }


        public virtual bool HasAdminAccess(AuthorizationContext filterContext)
        {
            string id = HttpContext.Current.Request.Params["id"];//collection["id"];
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id 参数为空");
            }
            UrlRouteBLL urlDAL = new UrlRouteBLL(null);
            var urlRouteInfo = urlDAL.GetInfoById(id);
            if (urlRouteInfo == null)
            {
                throw new InvalidOperationException(string.Format("参数 id={0} 不存在，检查是否过期。", id));
            }
            //if (!urlRouteInfo.EntityName.Equals("ETLSource", StringComparison.CurrentCultureIgnoreCase))
            //{
            //    throw new ArgumentException(string.Format("参数 id={0} 不存在，检查是否过期。", id));
            //}
            string userId = "gongcen";
            if (!string.IsNullOrEmpty(urlRouteInfo.UserID))
            {
                if (!urlRouteInfo.UserID.Equals(userId, StringComparison.CurrentCultureIgnoreCase))
                {
                    throw new ArgumentException(string.Format("参数 id={0} 对应的当前用户 {1} 错误，。", id, userId));
                }
            }
            return true;
        }

        private void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new HttpUnauthorizedResult(); //返回未授权Result
        }
    }
}